package com.mengwen.backstage.util;

import com.mengwen.backstage.pojo.Admin;
import com.mengwen.backstage.pojo.Partner;
import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author LiangYonghui
 * @date 2020/4/6 17:50
 * @description jwt工具类
 */
public class JwtUtil {
    public static final String SUBJECT = "mengwen";

    public static final long EXPIRE = 1000 * 60 * 60 * 24 * 7;  //过期时间，毫秒，一周

    //秘钥
    public static final String APPSECRET = "mengwen1124";

    /**
     * 生成管理员的jwt
     *
     * @param admin
     * @return
     */
    public static String geneAdminJsonWebToken(Admin admin) {

        if (admin == null || admin.getNickname() == null || admin.getHeadimgurl() == null || admin.getUnionid() == null
                || admin.getOpenid() == null) {
            return null;
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("adminHeadimgurl", admin.getHeadimgurl())
                .claim("adminUnionid", admin.getUnionid())
                .claim("adminNickname", admin.getNickname())
                .claim("adminOpenid", admin.getOpenid())
                .claim("role","admin")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();

        return token;
    }


    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {

        try {
            final Claims claims = Jwts.parser().setSigningKey(APPSECRET).
                    parseClaimsJws(token).getBody();
            return claims;

        } catch (Exception e) {
        }
        return null;

    }


    /**
     * 生成合伙人的jwt
     * @param partner
     * @return
     */
    public static String genePartnerJsonWebToken(Partner partner) {

        if (partner == null || partner.getNickname() == null || partner.getHeadimgurl() == null || partner.getUnionid() == null
                || partner.getOpenid() == null) {
            return null;
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("partnerHeadimgurl", partner.getHeadimgurl())
                .claim("partnerUnionid", partner.getUnionid())
                .claim("partnerNickname", partner.getNickname())
                .claim("partnerOpenid", partner.getOpenid())
                .claim("role","partner")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();

        return token;
    }





    private final static Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /*
     * 密文，用于加密解密Signature
     */
    private static final String JWT_SECRET = "fnarip*fudsgf_pbwei_65fa9sdf_jcewdiudsad56161bfof_1564d16";

    /**
     * pc端平台创建jwt
     *
     * @param id        用户的id
     * @param ttlMillis 过期的时间长度
     * @return token串
     * @throws Exception
     */
    public static String createJWT(String id,String type, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();// 签发jwt的时间
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder().setIssuedAt(new Date())// 签发时间
                .claim("unionId", id)// 用户的 unionid
                .claim("type",type)
                .signWith(signatureAlgorithm, key).setExpiration(new Date(nowMillis + ttlMillis));


        return builder.compact();
    }

    /**
     * 生成加密秘钥
     *
     * @return 秘钥
     */
    private static SecretKey generalKey() {
        String stringKey =  JWT_SECRET;// 秘钥
        byte[] encodedKey = Base64.decodeBase64(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * pc端验证token
     *
     * @param jwt token串
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws RuntimeException {
        SecretKey key = generalKey();
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
        return claims;
    }

//    /**
//     * 验证token并返回信息
//     * @param token
//     * @return
//     */
//    public static JWTCode judgeToken(String token){
//        try{
//            parseJWT(token);
//        }
//        catch (ExpiredJwtException e) {
//
//            logger.info("token过期！",e);
//            return JWTCode.OVERDUE;
//        } catch (Exception e) {
//
//            logger.info("token无效！",e);
//            return JWTCode.ERROR;
//        }
//        return JWTCode.SUCCESS;
//    }


    public static String getOpenId(HttpServletRequest request){
        String token = request.getHeader("token");
        String openId = "";
        try {
            openId = parseJWT(token).get("openId").toString();
        }
        catch (Exception e){
            System.out.println("tokn解析openId失败");

            return null;
        }
        return openId;
    }

    public static String getType(HttpServletRequest request){
        String token = request.getHeader("token");
        String type = "";
        try {
            type = parseJWT(token).get("type").toString();
        }
        catch (Exception e){
            System.out.println("tokn解析openId失败");
//            logger.error("tokn解析openId失败！",e);
            return null;
        }
        return type;
    }


    public static void main(String[] args) {


        String str = JwtUtil.createJWT("11", "type1", 111929292L);
        Claims claims = JwtUtil.parseJWT(str);
        System.out.println(claims);
//        String unionid = (String) claims.get("unionid");
//        System.out.println(unionid);

    }

}
